package com.feiluan.adapter;

import com.feiluan.service.BasicService;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

@Component
@Slf4j
@HttpRequestHandler.Sharable
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Autowired
    private BasicService basicService;

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        //100 Continue
        if (req instanceof FullHttpRequest) {
            // 获取请求的uri
            String result = "";
            if ("get".equalsIgnoreCase(req.method().name())) {
                result = convertGetTOPostRequest(req);
            }
            // 创建http响应
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    Unpooled.copiedBuffer(result, CharsetUtil.UTF_8));
            // 设置头信息
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
            //response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            // 将html write到客户端
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }


    private String convertGetTOPostRequest(FullHttpRequest request) {
        String uri = request.uri();
        String url = uri.split("\\?")[0];
        MultiValueMap<String, Object> map = getUrlMap(uri.split("\\?")[1]);
        ResponseEntity<String> result = basicService.postProxy("http://39.99.205.81:81" + url, null, map, String.class);
        return result.getBody();
    }


    /**
     * 将url中参数封装成map
     *
     * @param url
     * @return
     */
    public static MultiValueMap<String, Object> getUrlMap(String url) {

        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();

        if (!StringUtils.isEmpty(url)) {
            String[] arr = url.split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                requestBody.add(key, value);
            }
        }

        return requestBody;
    }


}
